package com.xwaf.platform.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.collect.Lists;
import com.xwaf.platform.common.api.entity.DynamicBean;
import com.xwaf.platform.common.excel.easy.excel.ExcelContext;
import com.xwaf.platform.common.excel.poi.util.ExportDynamicExcelWrapper;
import com.xwaf.platform.common.excel.poi.util.ExportExcel;
import com.xwaf.platform.common.excel.poi.util.ExportExcelUtil;
import com.xwaf.platform.common.excel.poi.util.ExportExcelWrapper;
import com.xwaf.platform.common.excel.poi.util.Student;
import com.xwaf.platform.system.api.entity.auth.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@Api(hidden = true)
@Controller("ExcelExport")
@RequestMapping("x/export")
public class ExcelExportController {

	@RequestMapping("/getExcel")
	public void getExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 准备数据
		List<Student> list = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			list.add(new Student(111, "张三asdf", "男"));
			list.add(new Student(111, "李四asd", "男"));
			list.add(new Student(111, "王五", "女"));
		}
		String[] columnNames = { "ID", "姓名", " 性别" };
		String fileName = "excel1";
		ExportExcelWrapper<Student> util = new ExportExcelWrapper<Student>();
		util.exportExcel(fileName, fileName, columnNames, list, response, ExportExcelUtil.EXCEl_FILE_2007);
	}

	/**
	 * easypoi导出实体列表
	 */
	@ApiOperation(value = "导出bean", notes = "导出", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
	@RequestMapping(value = "getExportBean", method = RequestMethod.GET)
	public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 准备数据
		List<User> list = Lists.newArrayList();
		User u = null;
		for (int i = 0; i < 10; i++) {
			u = new User();
			u.setId("1" + i);
			u.setActualName("10001" + i);
			u.setEmail("李聪" + i);
			list.add(u);
		}
		OutputStream out = null;
		try {
			String fileName = "easypoi导出列表.xlsx";
			String header = request.getHeader("User-Agent").toUpperCase();
			if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
				fileName = URLEncoder.encode(fileName, "utf-8");
				fileName = fileName.replace("+", "%20"); // IE下载文件名空格变+号问题
			} else {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
			}
			// 设置response参数，可以打开下载页面
			response.setContentType("application/x-msdownload;charset=utf-8");
			response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
			// 创建一个字节输出流
			out = response.getOutputStream();
			ExcelContext context = ExcelContext.newInstance("excel/User-config.xml"); // 导出配置文件
			Workbook workbook = null;
			if (list == null || list.isEmpty()) {
				workbook = context.createExcelTemplate("UserExport", null, null);
			} else {
				workbook = context.createExcel("UserExport", list);
			}
			// 设置底部统计栏
			Sheet sheet = workbook.getSheetAt(0);
			int lastRowNum = sheet.getLastRowNum();
			CellRangeAddress statisticMerge = new CellRangeAddress(lastRowNum + 1, lastRowNum + 1, 0, 10); // 单元格合并
			sheet.addMergedRegion(statisticMerge);
			Row statisticRow = sheet.createRow(lastRowNum + 1);
			Cell statisticCell = statisticRow.createCell(0);
			statisticCell.setCellValue("这是底部统计栏！！！！！！");
			workbook.write(out); // 写入流
			out.flush();
		} catch (final IOException e) {
			throw e;
		} finally {
			if (out != null)
				out.close();
		}
	}

	@RequestMapping("/getDynamicExcel")
	public void getDynamicExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 1 设置类成员属性
		HashMap<String, Object> propertyMap = new HashMap<String, Object>();
		propertyMap.put("id", Class.forName("java.lang.Integer"));
		propertyMap.put("name", Class.forName("java.lang.String"));
		propertyMap.put("address", Class.forName("java.lang.String"));

		// 准备数据
		List<DynamicBean> list = new ArrayList<DynamicBean>();
		for (int i = 0; i < 2; i++) {
			// 2生成动态 Bean
			DynamicBean bean = new DynamicBean(propertyMap);
			// 3 给 Bean 设置值
			bean.setValue("id", new Integer(1 + i));
			bean.setValue("name", "454" + i);
			bean.setValue("address", "789" + i);
			list.add(bean);
		}

		String[] columnNames = { "ID", "姓名", " 地址" };
		String fileName = "动态bean导出";
		ExportDynamicExcelWrapper util = new ExportDynamicExcelWrapper();
		util.exportExcel(fileName, fileName, columnNames, list, response, ExportExcelUtil.EXCEl_FILE_2007);
	}

	/**
	 * 
	 * <p>
	 * 导出excel，数据源为List<Map>
	 * <p>
	 * 
	 * @author 李聪 <br>
	 * @email xwaf_love@yeah.net <br>
	 * @since JDK 1.8<br>
	 * @date 2019年12月30日 上午9:32:03 <br>
	 * @see 无<br>
	 * @param request
	 * @param response
	 * @throws Exception
	 * @demo <br>
	 */
	@RequestMapping("/getMapExcel")
	public void getMapExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 准备数据
		List<LinkedHashMap<String, Object>> list = new ArrayList<LinkedHashMap<String, Object>>();
		LinkedHashMap<String, Object> map = null;
		for (int i = 0; i < 10; i++) {
			map = new LinkedHashMap<String, Object>();
			map.put(i + "0", i + "0");
			map.put(i + "1", "姓名：" + i);
			map.put(i + "2", "性别：" + i);
			list.add(map);
		}
		String[] columnNames = { "ID", "姓名", " 性别" };
		String fileName = "excel2";
		// 声明一个工作薄
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 生成一个表格
		XSSFSheet sheet = workbook.createSheet("MapExcel导出");
		// 设置表格默认列宽度为15个字节
		sheet.setDefaultColumnWidth(20);

		// 产生表格标题行
		XSSFRow row = sheet.createRow(0);
		XSSFCell cellHeader;
		for (int i = 0; i < columnNames.length; i++) {
			cellHeader = row.createCell(i);
			cellHeader.setCellStyle(ExportExcel.getHeaderStyle(workbook));
			cellHeader.setCellValue(new XSSFRichTextString(columnNames[i]));
		}
		ExportExcel.exportExcel(fileName, workbook, sheet, 1, list, response);
	}
}
